// xkImgCheck.cpp: implementation of the xkImgCheck class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "xkImgCheck.h"


//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

#include "ImageTIF.h"
#include "DDReadWriteFile.h"


xkImgCheck::xkImgCheck()
{

}

xkImgCheck::~xkImgCheck()
{

}


DWORD xkImgCheck::CheckFileBitPerSap(char *pFileName)
{
	int nBitPerSap = 8;

	DWORD dwType = 0;
	if( CheckFileType(pFileName,dwType) < 0 )
	{
		return -1;
	}

	switch(dwType)
	{
	case CXIMAGE_FORMAT_BMP:
	case CXIMAGE_FORMAT_JPG:
		{
			nBitPerSap = 8;
		}
		break;
	case CXIMAGE_FORMAT_TIF:
		{
			CImageTIF xImageTif;
			xImageTif.GetImgBitPerSap(pFileName,nBitPerSap);
		}
		break;
	case CXIMAGE_FORMAT_Old_NTB:
		{
			nBitPerSap = 12;
		}
		break;
	default:
		break;
	}

	return nBitPerSap;
}

DWORD xkImgCheck::CheckImageBitPerSap(zkImgBitInfo *pImgInfo)
{
	return 8;
}






int xkImgCheck::CheckFileType(char *pFileName,DWORD &dwFileType)
{
	int nRet = 0;
	BYTE *pBuf = NULL;

	do
	{	
		DDReadWriteFile xRead;
		nRet = xRead.DDCreateFile(pFileName);
		if( nRet < 0 )
		{
			break;
		}
		
		DWORD dwBytesToRead = 64;
		BYTE  cBuffer[64];
		
		nRet = xRead.DDOperatorFile(cBuffer,dwBytesToRead);
		if( nRet < 0 )
		{
			break;
		}
		
		nRet = ParseFileHeaderBuffer(cBuffer,dwBytesToRead,dwFileType);
		if( nRet < 0 )
		{
			break;
		}
			
		nRet = 0;
		
	} while(FALSE);
		
	return nRet;
}

int xkImgCheck::ParseFileHeaderBuffer(BYTE*pBuf,DWORD dwSize,DWORD &dwFileType)
{
	const unsigned char bmp[]  = {0x42,0x4d};
	const unsigned char tiff[] = {0x49,0x49,0x2a};
	const unsigned char tiff2[] = {0x4D,0x4D};
	const unsigned char jpg[]  = {0xff,0xd8,0xff};
	const unsigned char oldntb[]  = {0x53,0x4c};

	if( !memcmp(pBuf,bmp,sizeof(bmp)) ) //wmv
	{
		dwFileType = CXIMAGE_FORMAT_BMP;
	}
	else if( !memcmp(pBuf,tiff,sizeof(tiff)) || !memcmp(pBuf,tiff2,sizeof(tiff2)) )
	{
		dwFileType = CXIMAGE_FORMAT_TIF;
	}
	else if( !memcmp(pBuf,jpg,sizeof(jpg)) )
	{
		dwFileType = CXIMAGE_FORMAT_JPG;
	}
	else if( !memcmp(pBuf,oldntb,sizeof(oldntb)) )
	{
		dwFileType = CXIMAGE_FORMAT_Old_NTB;
	}
	else 
	{
		dwFileType = CXIMAGE_FORMAT_UNKNOWN;
		return -1;
	}

	return 0;
}